<script>
import {saveAs} from "file-saver";

export default {

  name: "Building",
  data() {
    return {
      //导出所需的id数组
      buildingIds: [],
      // 选中的数据条数
      multipleSelection: [],
      //模糊查询表单参数
      formInline: {
        buildingName: '',
        buildingCode: ''
      },

      rules: {
        buildingName: [
          {required: true, message: '楼栋名称不能为空', trigger: 'blur'},

        ],
        buildingAcreage: [
          {required: true, message: '楼栋面积不能为空', trigger: 'blur'},
          {pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确格式，可保留两位小数', trigger: ['blur', 'change']}
        ]

      },
      communityId: '',       //所属小区ID
      current: 1,     //当前页码
      size: 2,        //每页数据条数
      pages: 1,        //页面数
      total: 1,        //总数据条数
      buildings: [],   //楼栋列表
      communities: [],  //小区列表
      building: {
        "buildingId": null,
        "buildingName": "",
        "buildingAcreage": "",
        "remark": "",
        "communityId": ""
      },
      showSearchForm: true, // 控制搜索表单显示与隐藏的变量
      //楼栋表单信息
      dialogFormVisible: false, //表单显示变量
      formLabelWidth: '100px'   // 表单宽度
    }
  },
  methods: {

    reload() {
      location.reload()
    },

    toggleSearch() {
      this.showSearchForm = !this.showSearchForm; // 点击按钮切换显示与隐藏
    },
    //分页查询
    loadBuildings(event) {
      this.current = event.current;
      this.size = event.size;
      this.formInline = event.formInline;
      this.communityId = event.communityId;
      const queryParams = {
        current: this.current,
        size: this.size,
        buildingName: this.formInline.buildingName,
        buildingCode: this.formInline.buildingCode,
        communityId: this.communityId
      }
      this.$axios.get("/zyBuilding/buildings", {params: queryParams})
          .then(result => {
            if (result.data.code = "200") {
              console.log(result.data.data);
              this.buildings = result.data.data.records;
              this.pages = result.data.data.pages;
              this.total = result.data.data.total;
            }
          })
    },
    handleSizeChange(size) {
      this.size = size;
      this.loadBuildings({
        current: this.current,
        size: this.size,
        formInline: this.formInline,
        communityId: this.communityId
      });
    },
    handleCurrentChange(current) {
      this.current = current;
      this.loadBuildings({
        current: this.current,
        size: this.size,
        formInline: this.formInline,
        communityId: this.communityId
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getIndex(index) {
      return (this.current - 1) * this.size + index + 1;
    }
    ,
    onSubmit() {
      let formInline = this.formInline;
      this.loadBuildings({
        current: 1,
        size: this.size,
        formInline: formInline,
        communityId: this.communityId
      });
    }
    ,

    ClearOnSubmit() {
      this.formInline = {
        buildingCode: '',
        buildingName: ''
      }
      this.loadBuildings({
        current: this.current,
        size: this.size,
        formInline: this.formInline,
        communityId: this.communityId
      });
    }
    ,

    clearBuildingInformation() {
      this.building = {
        "buildingId": null,
        "buildingName": "",
        "buildingAcreage": "",
        "remark": "",
        "communityId": ""
      };
      this.dialogFormVisible = true;
    }
    ,
    clearForm() {
      this.$refs.form.clearValidate();// 清除表单验证信息
      this.$refs.form.resetFields(); // 重置表单字段
    }
    ,
    saveAndEditStudent(forName) {
      this.$refs[forName].validate(valid => {
            if (valid) {
              //通过id判断是否为null，判断进行添加或更新
              if (this.building.buildingId == null) {
                const username = localStorage.getItem("username");
                this.$axios.post("/zyBuilding/building/" + username, this.building)
                    .then(result => {
                      if (result.data.code = "200") {
                        this.loadBuildings({
                          current: this.current,
                          size: this.size,
                          formInline: this.formInline,
                          communityId: this.communityId
                        });
                        return this.$message({
                          message: '添加成功',
                          type: 'success',
                          duration: 2000
                        });
                      } else {
                        return this.$message.error({
                          message: '添加失败',
                          duration: 2000
                        });
                      }
                    });
              } else {
                const username = localStorage.getItem("username");
                this.$axios.put("/zyBuilding/building/" + username, this.building)
                    .then(result => {
                      if (result.data.code = "200") {
                        this.loadBuildings({
                          current: this.current,
                          size: this.size,
                          formInline: this.formInline,
                          communityId: this.communityId
                        });
                        return this.$message({
                          message: '修改成功',
                          type: 'success',
                          duration: 2000
                        });
                      } else {
                        return this.$message.error({
                          message: "修改失败",
                          duration: 2000
                        })
                      }
                    })
              }
              this.building = {
                "buildingId": null,
                "buildingName": "",
                "buildingAcreage": "",
                "remark": "",
                "communityId": ""
              };
            } else {
              this.dialogFormVisible = true;
            }
          }
      )
    }
    ,
    handleClose(done) {
      // 处理逻辑
      this.clearForm();
      // 可以调用done()来关闭dialog，或者不调用done()来阻止关闭
      done();
    }
    ,
    loadCommunities() {
      this.$axios.get("/zyCommunity/communities")
          .then(result => {
            console.log(result.data.data)
            this.communities = result.data.data;
          })
    }
    ,
    //更新回填信息
    editBuilding(building) {
      console.log(building)
      this.building = JSON.parse(JSON.stringify(building));
      this.dialogFormVisible = true;
    },

    editItem() {
      this.building = this.multipleSelection[0];
      this.editBuilding(this.building);
    },

    deleteItem() {
      const buildingIds = this.multipleSelection.map(item => item.buildingId);
      this.open(buildingIds)
    },
    deleteBuilding(buildingIds) {
      this.$axios.delete("/zyBuilding/building/" + buildingIds)
          .then(result => {
            if (result.data.code = "200") {
              if (this.multipleSelection.length > 1) {
                if (this.multipleSelection.length == this.buildings.length && this.current > 1) {
                  this.loadBuildings({
                    current: this.current - 1,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                } else if (this.multipleSelection.length == this.buildings.length && this.current == 1) {
                  this.loadBuildings({
                    current: this.current + 1,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                } else {
                  this.loadBuildings({
                    current: this.current,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                }
              } else {
                if (this.buildings.length == 1 && this.current > 1) {
                  this.loadBuildings({
                    current: this.current - 1,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                } else if (this.buildings.length == 1 && this.current == 1) {
                  this.loadBuildings({
                    current: this.current + 1,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                } else {
                  this.loadBuildings({
                    current: this.current,
                    size: this.size,
                    formInline: this.formInline,
                    communityId: this.communityId
                  });
                }
              }
            }
          })

    },

    open(buildingId) {
      this.$confirm('是否确认删除楼栋编号为' + '"' + buildingId + '"' + '的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteBuilding(buildingId);
        this.$message({
          type: 'success',
          message: '删除成功!',
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //导出到excel
    exportExcel() {
      this.$prompt('请输入导出文件名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        this.$axios.get("/zyBuilding/export?buildingIds=" + this.buildingIds, {responseType: 'arraybuffer'})
            .then(result => {
              const blob = new Blob([result.data], {type: 'applicationnd.openxmlformats-officedocument.spreadsheetml.sheet'});
              saveAs(blob, value + '.xlsx');
              this.loadBuildings({
                current: this.current,
                size: this.size,
                formInline: this.formInline,
                communityId: this.communityId
              });
              this.$message({
                type: 'success',
                message: '文件：' + value + '导出成功！'
              });
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消导出！'
        });
      });
    },

    //获取多行数据
    selectBuildingOneId(val) {
      this.buildingIds = [];
      for (let i = 0; i < val.length; i++) {
        this.buildingIds[i] = val[i].buildingId;
      }
      console.log(this.buildingIds)

    },
    //获取全部行数据
    selectBuildingAllIds(val) {
      this.buildingIds = [];
      for (let i = 0; i < val.length; i++) {
        this.buildingIds[i] = val[i].buildingId;
      }
      console.log(this.buildingIds)
    },

  },
  mounted() {
    this.communityId = localStorage.getItem("comId")
    this.loadBuildings({
      current: this.current,
      size: this.size,
      formInline: this.formInline,
      communityId: this.communityId
    });
    this.loadCommunities();
  }
}
</script>
<template>
  <div id="building">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" v-show="showSearchForm">
      <el-form-item label="楼栋名称">
        <el-input v-model="formInline.buildingName" placeholder="请输入楼栋名称" size="small"></el-input>
      </el-form-item>

      <el-form-item label="楼栋编码">
        <el-input v-model="formInline.buildingCode" placeholder="请输入楼栋编码" size="small"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit" size="small" style="background-color: #20B2AA">
          <i class="el-icon-search" style="width: 20px"></i>搜索
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-button @click="ClearOnSubmit" size="small">
          <i class="el-icon-refresh-right" style="width: 20px"></i>重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" size="small" @click="clearBuildingInformation">
      <i class="el-icon-plus" style="width: 20px"></i>新增
    </el-button>
    <el-button @click="editItem" type="success" size="small" :disabled="multipleSelection.length !== 1">
      <i class="el-icon-edit" style="width: 20px"></i>修改
    </el-button>
    <el-button type="danger" size="small" :disabled="multipleSelection.length == 0" @click="deleteItem">
      <i class="el-icon-delete" style="width: 20px"></i>删除
    </el-button>
    <el-button type="warning" size="small" @click="exportExcel">
      <i class="el-icon-download" style="width: 20px"></i>导出
    </el-button>

    <el-tooltip content="刷新" placement="top">
      <el-button icon="el-icon-refresh" circle style="float: right" size="small" @click="reload"></el-button>
    </el-tooltip>

    <el-tooltip content="隐藏搜索" placement="top">
      <el-button icon="el-icon-search" circle style="float: right" size="small" @click="toggleSearch"></el-button>
    </el-tooltip>


    <el-table
        :data="buildings"
        :cell-style="{'text-align':'center'}"
        :header-cell-style="{background:'#F8F8F9','text-align':'center',color:'#000'}"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @select="selectBuildingOneId"
        @select-all="selectBuildingAllIds">
      <el-table-column type="selection"></el-table-column>
      <el-table-column type="index" label="序号">
        <template slot-scope="scope">
          {{ getIndex(scope.$index) }}
        </template>
      </el-table-column>
      <el-table-column
          prop="buildingId"
          label="楼栋id"
          v-if="false"
      >
      </el-table-column>
      <el-table-column
          prop="buildingName"
          label="楼栋名称"
      >
      </el-table-column>
      <el-table-column
          prop="buildingCode"
          width="210px"
          label="楼栋编码">
      </el-table-column>
      <el-table-column
          prop="buildingAcreage"
          label="楼栋面积">
      </el-table-column>
      <el-table-column
          prop="zyCommunity.communityName"
          label="小区名称">
      </el-table-column>
      <el-table-column
          width="170px"
          prop="formattedCreateTime"
          label="创建时间">
      </el-table-column>
      <el-table-column
          prop="remark"
          label="备注">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
      >
        <template slot-scope="scope">
          <el-tooltip content="修改" placement="top">
            <el-button type="primary" icon="el-icon-edit" @click="editBuilding(scope.row)"
                       circle></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button type="danger" icon="el-icon-delete" circle @click="open(scope.row.buildingId)"></el-button>
          </el-tooltip>
          <!--          <el-button type="warning" @click="dialogFormVisible=true,editStudent(scope.row)" size="small" plain>-->
          <!--            更新-->
          <!--          </el-button>-->
          <!--          <el-button type="danger" @click="open(scope.row.id)" size="small" plain>删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <div id="pagination">
      <!--分页按钮-->
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="[2,3,4]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!--弹出式表单-->
    <el-dialog :title="building.buildingId==null?'添加楼栋':'修改楼栋'" :visible.sync="dialogFormVisible"
               :before-close="handleClose">
      <el-form :model="building" :rules="rules" ref="form">
        <el-form-item label="所属小区" :label-width="formLabelWidth">
          <el-select v-model="building.communityId" placeholder="请选择">
            <el-option
                v-for=" item in communities"
                :key="item.communityId"
                :label="item.communityName"
                :value="item.communityId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋名称" :label-width="formLabelWidth" prop="buildingName">
          <el-input v-model="building.buildingName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="楼栋面积" :label-width="formLabelWidth" prop="buildingAcreage">
          <el-input v-model="building.buildingAcreage" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="building.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false,clearForm()">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false,saveAndEditStudent('form')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<style scoped>

#pagination {
  text-align: center;
}

</style>
